Skip to content

MAINT: ensure file is closed - #162

Open
andyfaff wants to merge 1 commit into
reflectivity:mainfrom
andyfaff:fi
Open

MAINT: ensure file is closed#162
andyfaff wants to merge 1 commit into
reflectivity:mainfrom
andyfaff:fi

Conversation

@andyfaff

@andyfaff andyfaff commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

This is needed to ensure that a resource is definitely closed. At the moment the close doesn't happen if there's an exception raised after the yield, but before the file is closed.

@aglavic

aglavic commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator

Wouldn't it be cleaner to make this directly in a context manager and with testing for the actual class? No try/except etc required.

@contextmanager
def _possibly_open_file(f: Union[TextIO, str], mode: str = "wb") -> Generator[TextIO, None, None]:
    """
       ...
    """
    if not isinstance(f, str): # or alternatively isinstance(f, TextIOBase)
        yield f
    else:
        with open(f, mode) as g:
            yield g

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants